package cn.edu.swu.miniwebsvr.handler;

import cn.edu.swu.miniwebsvr.core.Handler;
import cn.edu.swu.miniwebsvr.core.Parameter;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class TimeHandler implements Handler {

    @Override
    public void handle(Parameter request, OutputStream response) {
        PrintWriter writer = new PrintWriter(response);

        // TODO: [222024321072050/邓琳馨] 构造完整的 HTTP 响应头和响应体
        try {
            // 获取当前时间
            LocalDateTime now = LocalDateTime.now();
            String currentTime = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            String timestamp = String.valueOf(System.currentTimeMillis());

            // 生成纯文本内容
            StringBuilder content = new StringBuilder();
            content.append("MiniWebSvr Server Time\n");
            content.append("=====================\n");
            content.append("Current Time: ").append(currentTime).append("\n");
            content.append("Timestamp: ").append(timestamp).append("\n");
            content.append("Date: ").append(now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))).append("\n");
            content.append("Time: ").append(now.format(DateTimeFormatter.ofPattern("HH:mm:ss"))).append("\n");
            content.append("12-Hour Format: ").append(now.format(DateTimeFormatter.ofPattern("hh:mm:ss a"))).append("\n");
            content.append("Day of Week: ").append(getEnglishDayOfWeek(now.getDayOfWeek().getValue())).append("\n");
            content.append("Day of Year: ").append(now.getDayOfYear()).append("\n");
            content.append("Timezone: ").append(System.getProperty("user.timezone")).append("\n");

            String plainContent = content.toString();
            byte[] contentBytes = plainContent.getBytes(StandardCharsets.UTF_8);

            // 构造完整的 HTTP 响应头
            writer.println("HTTP/1.1 200 OK");
            writer.println("Content-Type: text/plain; charset=UTF-8");
            writer.println("Content-Length: " + contentBytes.length);
            writer.println("Connection: close");
            writer.println("Server: MiniWebSvr/1.0");
            writer.println("Cache-Control: no-cache, no-store, must-revalidate");
            writer.println("Pragma: no-cache");
            writer.println("Expires: 0");
            writer.println(); // 空行分隔头部和正文

            // 写入响应体
            writer.print(plainContent);
            writer.flush();

            System.out.println("TimeHandler: 成功返回当前时间 " + currentTime);

        } catch (Exception e) {
            System.err.println("TimeHandler处理异常: " + e.getMessage());
            sendErrorResponse(writer, "时间处理器内部错误");
        }
    }

    /**
     * 获取英文星期几
     */
    private String getEnglishDayOfWeek(int dayOfWeek) {
        String[] days = {"", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
        return days[dayOfWeek];
    }

    /**
     * 发送错误响应
     */
    private void sendErrorResponse(PrintWriter writer, String message) {
        try {
            String errorContent = "Time Service Error\n" + message;
            byte[] errorBytes = errorContent.getBytes(StandardCharsets.UTF_8);

            writer.println("HTTP/1.1 500 Internal Server Error");
            writer.println("Content-Type: text/plain; charset=UTF-8");
            writer.println("Content-Length: " + errorBytes.length);
            writer.println("Connection: close");
            writer.println();
            writer.print(errorContent);
            writer.flush();
        } catch (Exception e) {
            System.err.println("发送错误响应失败: " + e.getMessage());
        }
    }
}